import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:url_launcher/url_launcher.dart';

import '../enum/map_type.dart';

// 地图工具类
class MapUtil {
  /// 获取可用的地图类型
  static Future<List<MapType>> getMapTypes() async {
    List<MapType> mapTypes = [
      MapType.apple,
      MapType.google,
      MapType.baidu,
      MapType.amap,
      MapType.tencent
    ];
    // 检查每种地图是否安装
    for (int i = 0; i < mapTypes.length; i++) {
      bool isInstalled = await MapUtil().isMapInstalled(mapTypes[i]);
      if (!isInstalled) {
        mapTypes.removeAt(i);
        i--;
      }
    }
    return mapTypes;
  }

  // 检查地图是否安装
  Future<bool> isMapInstalled(MapType types) async {
    debugPrint('Platform.isIOS : ${Platform.isIOS}');
    String url;
    switch (types) {
      case MapType.amap:
        url = Platform.isIOS ? 'iosamap://' : 'androidamap://';
        break;
      case MapType.google:
        url =
            Platform.isIOS ? 'comgooglemaps://' : 'https://www.google.com/maps';
        break;
      case MapType.baidu:
        url = 'baidumap://';
        break;
      case MapType.tencent:
        url = 'qqmap://';
        break;
      case MapType.apple:
        url = 'maps://';
        break;
      default:
        return false;
    }
    return await canLaunchUrl(Uri.parse(url));
  }

  // 打开Apple地图
  static Future<bool> openMap(
    double latitude,
    double longitude,
    MapType type,
    String appName,
    String poiName,
  ) async {
    String url = "";
    switch (type) {
      case MapType.amap:
        url = Platform.isIOS
            ? 'iosamap://path?sourceApplication=$appName&dlat=$latitude&dlon=$longitude&dname=$poiName&dev=0&t=0'
            : 'androidamap://route?sourceApplication=$appName&dlat=$latitude&dlon=$longitude&dev=0&t=0';
        break;
      case MapType.google:
        url = Platform.isIOS
            ? 'comgooglemaps://?daddr=$latitude,$longitude&directionsmode=driving'
            : 'https://www.google.com/maps/dir/?api=1&destination=$latitude,$longitude&travelmode=driving';
        break;
      case MapType.baidu:
        url =
            'baidumap://map/direction?destination=$latitude,$longitude&coord_type=wgs84&mode=driving&src=$appName';
        break;
      case MapType.tencent:
        url = 'qqmap://map/routeplan?type=drive&tocoord=$latitude,$longitude';
        break;
      case MapType.apple:
        url = 'http://maps.apple.com/?daddr=$latitude,$longitude&dirflg=d';
        break;
      default:
        break;
    }
    final mapUrl = Uri.parse(url);
    if (await canLaunchUrl(mapUrl)) {
      return launchUrl(mapUrl);
    } else {
      throw 'Could not launch $url';
    }
  }
}
